package server;

import view.ServerView;
import java.net.*;
import java.util.ArrayList;
import client.ClientView;


public class Server {

    // server port number
    static int serverPort   = 4444;
    private static Server instance = null;
    
    private static Socket clientSocket = null;
    private static ServerSocket sock = null;        
    private static int numConnections = 0;

    private static ArrayList<String> usersConnected = new ArrayList<String>();

    //Server server = new Server(serverPort);

    public Server() {
        startServer();
    }

    public void stopServer() {
        System.exit(0);
    }

    public void startServer() {

        ServerView.getInstance();
        
        try {            
            sock = new ServerSocket(serverPort);            
        } catch (Throwable e) {
            ServerView.printMessage("Error: " + e.getMessage());
            e.printStackTrace();
        }

        while(true) {
            ServerView.printMessage("Waiting for client to connect...\n");
            try {
                clientSocket = sock.accept();
                numConnections ++;
                ServerThread oneconnection = new ServerThread(clientSocket, numConnections, this);
                new Thread(oneconnection).start();
            } catch (Throwable e) {
                ServerView.printMessage("Error: " + e.getMessage());
            }
        }
    }

    public static Server getInstance() {
        if (instance == null) {
            instance = new Server();
        }
        return instance;
    }

    //add username to list of logged in users
    public static void addUser(String username) {
        usersConnected.add(username);
    }

    //remove username from list of logged in users
    public static void removeUser(String username) {
        usersConnected.remove(username);
    }

    public static String getUsers() {
        return usersConnected.toString();
    }

    //print a list of users logged in to manager
    public static void printUsers() {
        //usersConnected.add(ServerThread.getUsers());

        if (usersConnected.isEmpty()) {
            ClientView.printMessage("No users connected\n");
        }
        else {
            ClientView.printMessage(usersConnected.toString()+"\n");
        }

    }

    public void closeConnection() {
        //close connection to database
        try {
            sock.close();
        } catch (Throwable e) {
            ServerView.printMessage("Error: Connection could not be closed.\n");
        }
    }

}

